package mx.itesm.gda.clever.ui;

import java.io.IOException;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.texteditor.ITextEditor;

public class ScanHandler extends AbstractHandler {
	
	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		if (window == null) {
			throw new ExecutionException("no active workbench window"); //$NON-NLS-1$
		}
		
		final IWorkbenchPage page = window.getActivePage();
		if (page == null) {
			throw new ExecutionException("no active workbench page"); //$NON-NLS-1$
		}
		
		try {
			page.showView(TokensView.ID);
		} catch (final PartInitException exception) {
			throw new ExecutionException("error initializing the Tokens view"); //$NON-NLS-1$
		}
		
		final IWorkbenchPart part = page.getActivePart();
		final IEditorPart editor = page.getActiveEditor();
		if (part instanceof TokensView && editor instanceof ITextEditor) {
			try {
				((TokensView) part).scan((ITextEditor) editor);
			} catch (IOException exception) {
				MessageDialog.openError(HandlerUtil.getActiveShell(event), null, exception.getLocalizedMessage());
			}
		}
		
		return null;
	}
	
}
